﻿package Component
{

	import flash.display.MovieClip;
	import Game.Player;

	public class LoadScreen extends MovieClip
	{

		public var context:Context;
		private var avatars:Vector.<AvatarLoader > ;
		private var loaded:Boolean;

		public function LoadScreen()
		{
			avatars = new Vector.<AvatarLoader>();
			loaded = false;
		}

		// call this function when you are connected to server
		public function update()
		{
			if (loaded)
			{
				clean();
			}
			var avatar:AvatarLoader;
			var player:Player;
			var max:int = context.match.player_number;

			for (var i:int = 0; i < max; i++)
			{
				player = context.match.getPlayer(i);
				// instanciate new avatarloader
				avatar = new AvatarLoader(player.name);
				avatar.avatar.colorize(i)
				// adds to avatars
				avatars.push(avatar);
				// put on stage
				avatar.x = (width / (1 + max)) * (1 + i);
				avatar.y = height / 2;
				addChild(avatar);
			}
			loaded = true;
		}

		public function connected(id:int)
		{
			avatars[id].connected();
		}

		public function ready(id:int)
		{
			avatars[id].ready();
		}

		private function clean()
		{
			var avatar:AvatarLoader;
			loaded = false;
			while (avatars.length > 0)
			{
				avatar = avatars.pop();
				removeChild(avatar);
			}
		}
	}

}